from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import json
import time
import os
from selenium.common.exceptions import NoSuchElementException
from timetransfer import timetransfer

class Cookie_log():
    def __init__(self):
        chrome_options = Options()
        prefs = {'profile.default_content_setting_values' :{'notifications' : 2}}
        chrome_options.add_experimental_option('prefs',prefs)
        chrome_options.add_argument("window-size=1024,768")
        self.driver = webdriver.Chrome(options=chrome_options, executable_path=\
            r'C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Tools\chromedriver_win32\chromedriver.exe')
        self.driver.delete_all_cookies()
        print(self.driver.get_cookies())

    def delete_info(self,web_element):
        web_element.send_keys(Keys.CONTROL+'a')
        web_element.send_keys(Keys.DELETE)
    
    def ctrl_v(self,body_locator):
        body = self._wait_for(2,body_locator)
        action = ActionChains(self.driver)
        action.click(body).key_down(Keys.CONTROL+'a').key_up(Keys.CONTROL)\
            .key_down(Keys.BACKSPACE).key_up(Keys.BACKSPACE).perform()
        time.sleep(0.3)
        body = self.driver.find_element_by_xpath(body_locator)
        action.click(body).key_down(Keys.CONTROL+'v').key_up(Keys.CONTROL).perform()

    def _wait_for(self,time,locator):
        return WebDriverWait(self.driver,time,0.2).until(EC.presence_of_element_located(locator))

    def compulsive_click(self,web_element):
        ActionChains(self.driver).move_to_element(web_element).click(web_element).perform()

    def dict_attr(self,text):
        mass = text.split()
        keys = []
        values = []
        length = len(mass)
        if length%2 != 0:
            print('The attribute text is not complete.')
            return 
        for i in range(0,length,2):
            keys.append(mass[i][:-1])
            values.append(mass[i+1][:-1])
        return dict(zip(keys,values))

################################发布文章##################################################
    def _bjh_p(self,head_text,ready=False):
        url = 'https://baijiahao.baidu.com/builder/rc/edit?type=news&app_id=1591384705840207'
        if not ready:
            self.driver.get(url)
            return True
        head = WebDriverWait(self.driver,3,0.3).until(EC.presence_of_element_located(\
            (By.XPATH,"/html/body/div[1]/div/div/div[2]/div/div/div[1]/div[1]/div/div[2]/div[1]/form/div[1]/div/div/div/div[1]/div/div[1]/input")))
        self.delete_info(head)
        head.send_keys(head_text)
        frame = self.driver.find_element_by_css_selector('iframe')
        self.driver.switch_to.frame(frame)
        self.driver.find_element_by_xpath('/html/body/p').click()
        #ctrl + V

    def _163_p(self,head_text,ready=False):
        url = 'http://mp.163.com/article/postpage/W8567100657272114912?wemediaId=W8567100657272114912'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,"input[id='title']")))
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_css_selector("div[id='container'] > p").click()

    def _weibo_p(self,head_text,introduce,ready=False):
        url = 'https://card.weibo.com/article/v3/editor'
        if not ready:
            self.driver.get(url)
            return
        try:
            WebDriverWait(self.driver,2,0.3).until(EC.presence_of_element_located(\
                (By.XPATH,"/html/body/div/div/div[3]/div/div[1]/div[2]/div/div/div/p[2]/a"))).click()
        except Exception:
            pass
        head = WebDriverWait(self.driver,2,0.3).until(EC.presence_of_element_located(\
                (By.CSS_SELECTOR,'div[class="title"] > div + textarea')))
        self.delete_info(head)
        head.send_keys(head_text)
        intro = self.driver.find_element_by_css_selector('div[class="preface"] > input')
        self.delete_info(intro)
        intro.send_keys(introduce)
        self.driver.find_element_by_css_selector('div[contenteditable="true"] > p').click()

    def _toutiao_p(self,head_text,ready=False):
        url = 'https://mp.toutiao.com/profile_v3/graphic/publish'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,"input[id='title']")))  
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_css_selector('div[class="text-editor"] > div > div[contenteditable]').click()
        #首发
        self._wait_for(3,(By.XPATH,'//*[@id="originalBtn"]/label/div/input')).click()
        #self.driver.find_element_by_xpath('//*[@id="originalBtn"]/label/div/input').click()
        self._wait_for(5,(By.CSS_SELECTOR,'div[class="original-main"] button[class$="primary"]')).click()
    


    def _qtt_p(self,head_text,tags,ready=False):
        url = 'https://mp.qutoutiao.net/publish-content/article'
        if not ready:
            self.driver.get(url)
            return
        #可能有消息弹窗
        try:
            m_box = self._wait_for(2,(By.CSS_SELECTOR,'div[class*="el-message-box"]'))
            if self.dict_attr(m_box.get_attribute('style'))['display'] != 'none':
                m_box.find_element_by_css_selector('div[class$="btns"] > button + button').click()
        except Exception:
            pass
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,'.el-input input')))
        self.delete_info(head)
        head.send_keys(head_text)
        frame = self.driver.find_element_by_css_selector("iframe")
        self.driver.switch_to.frame(frame)
        body_locator = (By.XPATH,'/html/body/p')
        self.ctrl_v(body_locator)
        self.driver.switch_to.parent_frame()
        #三图，自动生成
        self._wait_for(2,(By.XPATH,'//label[contains(text(),"封面")]/..//img'))

        #分类，貌似是自动，是一个下拉框，尽量分割成函数
        classfication = self.driver.find_elements_by_xpath(\
            '//label[contains(text(),"分类")]/..//input')
        classfication.click()
        self._wait_for(2,\
            (By.XPATH,'//div[@role="tooltip"]//dt[text()="汽车"]/../dl[1]/dd[text()="汽车资讯"]')).click()
        self.driver.find_element_by_xpath(\
            '//div[@role="tooltip"]//dt[text()="汽车"]/../dl[1]/dd[text()="车评"]').click()
        self.driver.find_element_by_xpath(\
            '//div[@role="tooltip"]//dt[text()="汽车"]/../dl[1]/dd[text()="新车"]').click()

        #tags
        tags_input = self.driver.find_element_by_xpath('//label[contains(text(),"标签")]/..//input')
        tags_input.click()
        for tag in tags:
            tags_input.send_keys(tag)
            tags_input.send_keys(Keys.ENTER)
        #原创
        origin = self.driver.find_element_by_xpath('//label[contains(text(),"原创")]/../div').find_element_by_xpath(\
            '//span[contains(text(),"是")]/../span/input')
        ActionChains(self.driver).move_to_element(origin).click(origin).perform()#强制点击
        self._wait_for(2,(By.CSS_SELECTOR,'div[aria-label="警告"]')).find_element_by_xpath(\
            '//span[contains(text(),"知道了")]/../../button[2]').click()
        #发布
        self.driver.find_element_by_css_selector('div.handle-btns')\
            .find_element_by_xpath('//span[text()="发布"]/../../button[1]').click()

    def _cjh_p(self,head_text,introduce,ready=False):
        url = 'https://chejiahao.autohome.com.cn/My/AuthorArticles/add/0#pvareaid=2808351'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,"input[id='title']")))
        self.delete_info(head)
        head.send_keys(head_text)
        intro = self.driver.find_element_by_css_selector("textarea[id='textDesc']")
        self.delete_info(intro)
        intro.send_keys(introduce)
        self.driver.find_element_by_xpath('//*[@id="editor"]/div[1]/p').click()
        
    def _ifeng_p(self,head_text,ready=False):
        url = 'http://fhh.ifeng.com/publish/article'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,'//*[@id="J_articleTitle"]')))
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_xpath('//*[@id="editor"]/div[1]/p').click()
        
    def _souhu_p(self,head_text,ready=False):
        url = 'https://mp.sohu.com/mpfe/v3/main/news/addarticle?contentStatus=1'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.XPATH,'//*[@id="content-all"]/div/div[3]/div[1]/input')))
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_xpath('//*[@id="editor"]/div[1]/p').click()

    def _youche_p(self,head_text,ready=False):
        url = 'http://mp.youcheyihou.com/#/article-edit'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.XPATH,'//*[@id="content-all"]/div/div[3]/div[1]/input')))
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_xpath('//*[@id="editor"]/div[1]/p').click()

    def _yidian_p(self,head_text,ready=False):
        url = 'https://mp.yidianzixun.com/#/Writing/articleEditor'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.XPATH,'//*[@id="managePage"]/div[3]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/input')))
        self.delete_info(head)
        head.send_keys(head_text)
        self.driver.find_element_by_xpath('//*[@id="managePage"]/div[3]/div[2]/div/div/div/div[2]/div/div[2]/div[4]/div[1]/div').click()

    def _sina_p(self,head_text,ready=False):
        url = 'http://mp.sina.com.cn/main/editor?vt=4#/SendArt/Edit'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.XPATH,'//*[@id="root"]/div/div/div/section[1]/section[1]/aside/textarea')))
        self.delete_info(head)
        head.send_keys(head_text)
        frame = self.driver.find_element_by_css_selector("iframe")
        self.driver.switch_to.frame(frame)
        self.driver.find_element_by_xpath('/html/body').click()

    def _dayu_p(self,head_text,ready=False):
        url = 'https://mp.dayu.com/dashboard/article/write?spm=a2s0i.db_contents.menu.3.67c73caarUGcXk'
        if not ready:
            self.driver.get(url)
            return
        head = WebDriverWait(self.driver,20,0.3).until(EC.presence_of_element_located(\
            (By.CSS_SELECTOR,"input[id='title']")))
        self.delete_info(head)
        head.send_keys(head_text)
        frame = self.driver.find_element_by_css_selector("iframe")
        self.driver.switch_to.frame(frame)
        self.driver.find_element_by_xpath("/html/body/p").click()


#######################收集链接#############################################
    def _163_p(self):
        url = 'http://mp.163.com/article/postpage/W8567100657272114912?wemediaId=W8567100657272114912'
        self.driver.get(url)

    def _weibo_p(self):
        url = 'https://card.weibo.com/article/v3/editor#/draft'
        self.driver.get(url)
    def _toutiao_p(self):
        url = 'https://mp.toutiao.com/profile_v3/graphic/publish'
        self.driver.get(url)        
    def _dayu_p(self):
        url = 'https://mp.dayu.com/dashboard/article/write?spm=a2s0i.db_contents.menu.3.67c73caarUGcXk'
        self.driver.get(url)

    def _qtt_c(self,windows):#链接只能通过点击获得，点击会产生新窗口
        url = 'https://mp.qutoutiao.net/publish-content/article'
        self.driver.get(url)
        self._wait_for(2,(By.CSS_SELECTOR,'div.content-article a')).click()#选择第一个
        #找到新窗口
        new_handle = list(set(self.driver.window_handles) - set(windows.values()))[0]
        url = self.driver.switch_to.window(new_handle)
        self.driver.close()
        return url



    def _cjh_p(self):
        url = 'https://chejiahao.autohome.com.cn/My/AuthorArticles/add/0#pvareaid=2808351'
        self.driver.get(url)

    def _ifeng_p(self):
        url = 'http://fhh.ifeng.com/publish/article'
        self.driver.get(url)
    def _souhu_p(self):
        url = 'https://mp.sohu.com/mpfe/v3/main/news/addarticle?contentStatus=1'
        self.driver.get(url)
    def _youche_p(self):
        url = 'http://mp.youcheyihou.com/#/article-edit'
        self.driver.get(url)

    def _yidian_p(self):
        url = 'https://mp.yidianzixun.com/#/Writing/articleEditor'
        self.driver.get(url)

    def _sina_p(self):
        url = 'http://mp.sina.com.cn/main/editor?vt=4#/SendArt/Edit'
        self.driver.get(url)

#######################收集链接#############################################